package com.pjbao.Service;

import com.pjbao.Service.dao.G9ImgRepository;
import com.pjbao.Service.dao.ImgRepository;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 邱鹏 on 2016/10/15.
 */
@RestController("/dataService/base64Img")
public class ResourceController {
    @Autowired
    ImgRepository imgRepository;
    @Autowired
    G9ImgRepository g9ImgRepository;



    @GetMapping("/G202/{cid}")
    public void getImage(@PathVariable String cid, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        String string = " ";
        G202_Model g202_model = imgRepository.findByData_cid(cid);
        string = g202_model.getData().getPhotos();
        byte[] bytes=generateImage(string);
        out.write(bytes);
        out.flush();
        out.close();
    }
    @GetMapping("/G9/{cid}")
    public void getG9Image(@PathVariable String cid, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        String string = " ";
        G9Model g9Model = g9ImgRepository.findByData_Retdata_PersonBase_DocumentNo(cid);
        string = g9Model.getData().getRetdata().getDegree().getPhoto();
        System.out.println(string);
        byte[] bytes=generateImage(string);
        out.write(bytes);
        out.flush();
        out.close();
    }

    public byte[] generateImage(String imgStr) throws IOException {// 对字节数组字符串进行Base64解码并生成图片
        byte[] bytes = null;
        if (imgStr == null) {
        } else {
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
        }
        return bytes;
    }
}
